class Device < ActiveRecord::Base
    has_many :device_features, :dependent => :destroy
    has_many :features, :through => :device_features
    has_many :craftrolls
    belongs_to :size
    validates_presence_of :name,:fd, :mr, :timefactor 
    validates_associated :device_features
    
    after_update :save_device_features
    
    def new_device_feature_attributes=(device_feature_attributes)
      device_feature_attributes.each do |attributes|
        device_features.build(attributes)
      end
    end
  
    def existing_device_feature_attributes=(device_feature_attributes)
      device_features.reject(&:new_record?).each do |device_feature|
       attributes = device_feature_attributes[device_feature.id.to_s]
       if attributes
         device_feature.attributes = attributes
       else
         device_features.delete(device_feature)
       end
   end
 end
 
  
  def save_device_features
    device_features.each do |device_feature|
      device_feature.save(false)
    end
  end

  def get_ts_max
    @maxts=0
    self.device_features.each{|x| @maxts=(@maxts>=x.get_ts)?@maxts:(x.get_ts)}
    @maxts
  end
  
  def get_ts_sum
    @sumts=0
    self.device_features.each{|x| @sumts+=x.get_ts}
    @sumts
  end
  
  def marketValue
    self.cmv=(self.fd.*self.get_ts_max*self.get_cs_score)/(self.timefactor+self.mr).to_f
    self.cost=(self.cmv/3)*10
    self.actualcost=self.cost
    self.remainingcost=self.cost
    self.save
    self.cmv
  end
  
  def add_roll(roll)
    @cdc=self.fd+self.get_ts_max
    self.craftrolls<<Craftroll.create(:roll=>roll)
    self.save
    if @cdc<=roll 
      self.remainingcost-=@cdc*roll
      if self.remainingcost<=0
        self.remainingcost=0
      end
      self.save
    end
    if @cdc>roll+5
      self.actualcost+=self.cost/2
      self.save
    end
    
  end
  
  def get_cs_score
    @cs=0
    @cs=(self.fd/2)+self.get_ts_sum
    @cs
  end
  
  def reset_cost
    if !self.craftrolls.empty?
     for x in self.craftrolls
       x.destroy
     end
    end
    self.actualcost=self.cost
    self.remainingcost=self.cost
    self.save
  end
end

